package com.kun.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Set;
import java.util.HashSet;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.kun.config.EntityRedisSerializer;
import com.kun.entity.Book;
import com.kun.entity.User;
import com.kun.service.BookService;

/**
 * @description:用户书库
 * @author: KM
 * 2018年3月30日
 */
@Controller
@RequestMapping("/library")
public class UserLibrary{
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private SetOperations<String, Object> setOperations;
	
	@Autowired
    protected RedisTemplate<String, Object> redisTemplate;
	
	@Autowired
	private BookService bookService;
	
	private final String USER_BOOK_SET = "USER_BOOK_SET";
	private Subject currentUser;
	private User user;
	
	//收藏图书
	@RequestMapping(value="/collectBook",method=RequestMethod.POST)
	@ResponseBody
	public String addBook(int bookid,HttpServletRequest req,HttpServletResponse resp) throws UnsupportedEncodingException{
		currentUser = SecurityUtils.getSubject(); 
		if(currentUser.getPrincipal()!=null){//是否登录
			user = (User) currentUser.getPrincipal();
			redisTemplate.setValueSerializer(new EntityRedisSerializer());
			setOperations.add(user.getUsername() + USER_BOOK_SET, bookid);
		}else{
			Set<Book> bookSet = getCookieBookSet(req);
			Book book = bookService.selectBookById(bookid);
			bookSet.add(book);
			logger.info(bookSet.size()+"");
			String  JSONString = JSON.toJSONString(bookSet, true);
			Cookie cookie = new Cookie(USER_BOOK_SET,URLEncoder.encode(JSONString, "UTF-8"));
            cookie.setPath("/");
            cookie.setMaxAge(30*24*60*60);
            resp.addCookie(cookie);
		}
		return "success";
	}

	//取消收藏
	@RequestMapping("/unCollectBook")
	@ResponseBody
	public String delBook(Book book,HttpServletRequest req,HttpServletResponse resp) throws UnsupportedEncodingException{
		currentUser = SecurityUtils.getSubject(); 
		if(currentUser.getPrincipal()!=null){//是否登录
			user = (User) currentUser.getPrincipal();
			redisTemplate.setValueSerializer(new EntityRedisSerializer());
			logger.info("是否保存有该图书----------" + setOperations.isMember(user.getUsername() + USER_BOOK_SET, book.getBookid()));
			if(setOperations.isMember(user.getUsername() + USER_BOOK_SET, book.getBookid())){
				setOperations.remove(user.getUsername() + USER_BOOK_SET, book.getBookid());
			}
		}else{
			Set<Book> bookSet = getCookieBookSet(req);
			logger.info("删除前：-------"+bookSet.size());
			bookSet.remove(book);
			logger.info("删除后：-------"+bookSet.size());
			String  JSONString = JSON.toJSONString(bookSet, true);
			Cookie cookie = new Cookie(USER_BOOK_SET,URLEncoder.encode(JSONString, "UTF-8"));
            cookie.setPath("/");
            cookie.setMaxAge(30*24*60*60);
            resp.addCookie(cookie);
		}
		return "success";
	}
	
	//获取所有收藏图书
	@RequestMapping("")
	public String getBook(HttpServletRequest req,Model model){
		Set<Book> bookSet = new HashSet<Book>();
		currentUser = SecurityUtils.getSubject(); 
		if(currentUser.getPrincipal()!=null){//是否登录
			user = (User) currentUser.getPrincipal();
			redisTemplate.setValueSerializer(new EntityRedisSerializer());
			Set<Object> lb = setOperations.members(user.getUsername() + USER_BOOK_SET);
			for (Object object : lb) {
				Book b = bookService.selectBookById((int)object);
				bookSet.add(b);
			}
		}else{
			bookSet = getCookieBookSet(req);
		}
		model.addAttribute("bookSet", bookSet);
		return "library";
	}
	
	
	/**
	 * 获取cookie保存的图书
	 * */
	public Set<Book> getCookieBookSet(HttpServletRequest req){
		Set<Book> sb = new HashSet<Book>();
		Cookie[] cookies = req.getCookies();
		if (null != cookies && cookies.length > 0) {
			for(int i=0;i<cookies.length;i++){
	    		Cookie cookie = cookies[i];
	    		if((USER_BOOK_SET).equals(cookie.getName())){//该用户是否有保存书在cookie
	    			String cv = cookie.getValue();
	    			if(!"".equals(cv)&&cv!=null){
						try {
							sb = JSON.parseObject(URLDecoder.decode(cv, "UTF-8"), new TypeReference<Set<Book>>(){});
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
							logger.error("解码发生错误。。。");
						}
	    			}
	    			break;
	    		}
	    	}
		}
		return sb;
	}
	
	
}
